﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class Test : System.Web.UI.Page
{
    //static DataTable dt_sta = new DataTable();
    static string where = string.Empty;
    static DataSet dst = new DataSet();

    protected void Page_Load(object sender, EventArgs e)
    {
        //BindChar();

        if (!IsPostBack)
        {
            //统计
            // BindChar();
            //BindTable();
            //BindKeyUnitType();

            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand("KeyUnit5Power1", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            dst.Clear();
            dap.Fill(dst, "units");

            BindChar(dst);
            //绑定显示登录者的大队或支队编号的重点单位
            string DepartmentID = string.Empty;
            DepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
            //DepartmentID = "1301000";

            ViewState.Add("DepartmentID", DepartmentID);
            string tdid = DepartmentID.Substring(0, 4) + "5" + DepartmentID.Substring(5, 2);
            where = " DepartmentID='" + DepartmentID + "' or DepartmentID='" + tdid + "'";
            gvBind(where, 0);

            DBCls db = new DBCls();
            DataTable dt = new DataTable();



            //绑定支队和大队列表
            string sqlzhidui = "select departmentid,fullname from Account_Departments where departmentid like'%000' and departmentid <> 1300000";
            dt.Clear();
            dt = db.QueryDataTable(sqlzhidui, "zhidui");
            if (dt.Rows.Count > 0)
            {
                //支队
                ddlZD.Items.Clear();
                ddlZD.DataSource = dt;
                ddlZD.DataTextField = "fullname";
                ddlZD.DataValueField = "departmentid";
                ddlZD.DataBind();
                //大队
                ddlZD_SelectedIndexChanged(sender, e);
            }

            //绑定重点单位类型
            dt.Clear();
            dt = db.QueryDataTable("select KeyUnitTypeID,KeyUnitTypeDescript from KeyUnitType order by cast( keyunittypeid  as int)", "KeyUnitType");
            if (dt.Rows.Count > 0)
            {
                ddlUnitType.Items.Clear();

                ddlUnitType.DataSource = dt;
                ddlUnitType.DataTextField = "KeyUnitTypeDescript";
                ddlUnitType.DataValueField = "KeyUnitTypeID";
                ddlUnitType.DataBind();


                ddlUnitType.Items.Insert(0, new ListItem("全部", "全部"));

            }

            //重点单位类型对照表

            string sql = "select KeyUnitTypeDescript,KeyUnitTypeName from KeyUnitType order by cast( keyunittypeid  as int) ";
            SqlDataReader sqlReader = db.SqlReader(sql);

            DataTable Dt = new DataTable();
            DataRow dr;
            Dt.Columns.Add("KeyUnitTypeDescript", typeof(string));    //第几类
            Dt.Columns.Add("KeyUnitTypeName", typeof(string));   //类型全称



            while (sqlReader.Read())
            {
                dr = Dt.NewRow();
                dr[0] = sqlReader[0].ToString();
                dr[1] = sqlReader[1].ToString();

                Dt.Rows.Add(dr);
            }
            sqlReader.Close();
            this.DataList1.DataSource = new DataView(Dt);
            this.DataList1.DataBind();

            //登陆者权限显示控制
            string p4 = DepartmentID.Substring(3, 1).ToString();    //总队
            string p5 = DepartmentID.Substring(4, 1).ToString();
            if (p4 == "0")
            {
                //总队
                ddlZD.Enabled = true;
                ddlDD.Enabled = true;
            }
            else if (p5 == "0" || p5 == "1")
            {
                //支队,固定ddlZD
                string s4 = DepartmentID.Substring(0, 4).ToString();
                ddlZD.SelectedValue = s4 + "000";
                //重新绑定大队
                ddlZD_SelectedIndexChanged(sender, e);
                ddlZD.Enabled = false;
                ddlDD.Enabled = true;

            }
            else if (p5 == "2")
            {
                //大队 固定ddlDD
                string s4 = DepartmentID.Substring(0, 4).ToString();
                ddlZD.SelectedValue = s4 + "000";
                //重新绑定大队
                ddlZD_SelectedIndexChanged(sender, e);
                ddlDD.SelectedValue = DepartmentID;
                ddlZD.Enabled = false;
                ddlDD.Enabled = false;
            }
        }
        else
        {
            BindChar(dst);
        }
    }

    #region

    protected void ListPageContral1_PageSizeChange(int pageSize, int PageIndex)
    {
        where = lblTempWhere.Text;
        gvBind(where, PageIndex);

        //Response.Write("<script language=javascript>alert('条件：" + where + "')</script>");
    }


    protected void ddlZD_SelectedIndexChanged(object sender, EventArgs e)
    {
        //绑定大队 消防科
        string departmentid = ddlZD.SelectedValue.ToString();
        departmentid = departmentid.Substring(0, 4);
        string sqldadui = "select departmentid,fullname,shortname from Account_Departments where departmentid like'" + departmentid + "%' and ( shortname like'%大队' or shortname like'%消防科' or shortname like'%防火处') and shortname not in ( '特勤大队') ";

        // Response.Write("<script language=javascript>alert('SQL:" + sqldadui + "')</script>");	

        DBCls db = new DBCls();
        DataTable dt = new DataTable();
        dt = db.QueryDataTable(sqldadui, "dadui");
        if (dt.Rows.Count > 0)
        {
            ddlDD.Items.Clear();
            ddlDD.DataSource = dt;
            ddlDD.DataTextField = "fullname";
            ddlDD.DataValueField = "departmentid";
            ddlDD.DataBind();

            ddlDD.Items.Insert(0, new ListItem("全部", "全部"));

        }
        //gv没有数据时刷新后不显示“没有数据”
        //没有数据时重新绑定gv
    }
    void gvBind(string where, int pageIndex)
    {



        try
        {
            ////GetWhere();
            //string where = " DepartmentID='" + DepartmentID + "' ";
            List<PerformanceInfo> list = Performance.GetList(ListPageContral1.PageSize, pageIndex, where);

            gvDW.DataSource = list;
            gvDW.DataBind();
            ListPageContral1.ItemCount = Performance.GetCount(where);

            //DBCls db = new DBCls();
            //string sql = "select PerformanceID,KeyUnitName,PerformanceState from Performance where DepartmentID='" + DepartmentID + "'";

            //dt_sta = db.QueryDataTable(sql, "Performance");

            //如果没有数据
            if (list.Count < 0)
            {

                DataTable dt = new DataTable();
                dt.Columns.Clear();

                dt.Columns.Add("PerformanceID");
                dt.Columns.Add("KeyUnitName");
                dt.Columns.Add("PerformanceState");

                dt.Columns.Add("查看");
                dt.Columns.Add("编辑");
                dt.Columns.Add("删除");

                if (dt.Rows.Count == 0)
                {
                    dt.Rows.Add(dt.NewRow());
                }

                this.gvDW.DataSource = dt;
                this.gvDW.DataBind();

                //this.GridView1.HeaderStyle.Height = Unit.Pixel(10);
                // this.GridView1.RowStyle.Height = Unit.Pixel(7);
                int columnCount = dt.Columns.Count;
                //移除单元格数据
                gvDW.Rows[0].Cells.Clear();
                //添加新单元格
                gvDW.Rows[0].Cells.Add(new TableCell());
                //合并单元格
                gvDW.Rows[0].Cells[0].ColumnSpan = columnCount;
                //设置单元格的显示的信息
                gvDW.Rows[0].Cells[0].Text = "没有记录";
                // 设置单元格的样式，居中显示
                gvDW.Rows[0].Cells[0].Style.Add("text-align", "center");
                gvDW.Rows[0].Cells[0].Style.Add("color", "red");
                gvDW.Rows[0].ForeColor = System.Drawing.Color.Red;
                //隐去 ID
                //  GridView1.Columns[0].Visible = false;
                //this.GridView1.DataSource = dt;
                //this.GridView1.DataBind();
            }
            // Response.Write("<script language=javascript>alert('条件：" + where + "')</script>");

        }
        catch (Exception ex)
        {
            Response.Write("<script language=javascript>alert('databing错误:" + ex.Message + "！')</script>");
            return;
        }

    }

    protected void gvDW_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            int num = Convert.ToInt32(e.CommandArgument);//得行号
            string id = this.gvDW.DataKeys[num]["PerformanceID"].ToString();//得主键值

            DBCls db = new DBCls();

            string s = e.CommandName.ToString();
            //查看
            if (s == "Select")
            {
                Response.Redirect("KeyUnitView.aspx?id=" + id + "");
            }
            //修改
            if (s == "Edit")
            {
                Response.Redirect("KeyUnitEdit.aspx?id=" + id + "");
            }
            //删除
            if (s == "Delete")
            {
                string sqlPerformance = "delete Performance where PerformanceID='" + id + "'";
                string sqlPerformancePic = "delete PerformancePic where PerformanceID='" + id + "'";

                try
                {


                    DataTable dt = db.QueryDataTable("select PictureUrl from performancepic where PerformancePicID='" + id + "'", "picpath");

                    if (db.ExcuteSql2(sqlPerformance, sqlPerformancePic))
                    {
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                string path = dt.Rows[i][0].ToString();

                                string allPath = Request.MapPath("") + "//" + @path;
                                try
                                {
                                    File.Delete(allPath);
                                }
                                catch (Exception ex) { }

                            }
                        }
                        Response.Write("<script language=javascript>alert('删除成功')</script>");
                    }
                    else
                    {
                        Response.Write("<script language=javascript>alert('删除失败！')</script>");
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("<script language=javascript>alert('删除失败！" + ex.Message + "')</script>");
                }

                //重新绑定
                this.gvBind(where, 0);

            }
        }
        catch (Exception ex)
        {
            Response.Write("<script language=javascript>alert('操作失败！gridview-rowcommand错误！" + ex.Message + "！')</script>");
        }
    }
    protected void gvDW_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[1].Attributes.Add("class", "text");
        }
        int i;
        int count = this.gvDW.Rows.Count;
        //  string id = this.GridView1.DataKeys[e.Row.RowIndex]["ProductID"].ToString();
        for (i = 0; i <= count; i++)
        {
            //首先判断是否是数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ////当鼠标停留时更改背景色
                //e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#F5F5F5'");
                ////当鼠标移开时还原背景色
                //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");

                //当鼠标放上去的时候 先保存当前行的背景颜色 并给附一颜色 
                e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#F5F5F5',this.style.fontWeight='';");
                //当鼠标离开的时候 将背景颜色还原的以前的颜色 
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");

                //添加删除提示
                if (e.Row.Cells.Count > 5)
                {
                    e.Row.Cells[5].Attributes.Add("onclick", "return confirm('确定删除吗？');");
                }
            }
        }
    }
    protected void gvDW_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //string id = this.gvDW.DataKeys[e.NewEditIndex].Values[0].ToString();
        ////清空后赋值
        //this.ViewState.Clear();
        //ViewState.Add("PerformanceID", id.ToString());
        ////设置可编辑
        //this.txtUserName.Enabled = true;
        //this.ddlCompany.Enabled = true;
        //this.rblSex.Enabled = true;
        //this.rblPost.Enabled = true;
        //this.txtAge.Enabled = true;
        //this.txtTele.Enabled = true;
        //this.txtMoblie.Enabled = true;
        //this.txtAddress.Enabled = true;
        //this.txtEmail.Enabled = true;
        //this.txtUserRemark.Enabled = true;
    }
    protected void gvDW_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void gvDW_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //this.GridView1.PageIndex = e.NewPageIndex;
        //this.GridView1.DataSource = dt_sta;
        //this.GridView1.DataBind();
    }

    //查询
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string DepartmentID = ddlDD.SelectedValue.ToString();
        where = "";
        if (DepartmentID == "全部")
        {
            DepartmentID = ddlZD.SelectedValue.ToString().Substring(0, 4).ToString();
            where = "DepartmentID like '" + DepartmentID + "%'";
        }
        else
        {

            if (DepartmentID.Substring(4, 1).ToString() == "2") //大队
            {
                if (rblPolice.SelectedValue == "派出所")
                {
                    DepartmentID = DepartmentID.Substring(0, 4) + "5" + DepartmentID.Substring(5, 2).ToString();
                    where = "DepartmentID like '" + DepartmentID + "%'";
                }
                else if (rblPolice.SelectedValue == "大队")
                {
                    //DepartmentID = DepartmentID;
                    where = "DepartmentID like '" + DepartmentID + "%'";
                }
                else
                {
                    string police = DepartmentID.Substring(0, 4) + "5" + DepartmentID.Substring(5, 2).ToString();
                    where = "DepartmentID in ( '" + DepartmentID + "','" + police + "')";
                }
            }
            else
            {
                DepartmentID = DepartmentID.Substring(0, 5).ToString();
                where = "DepartmentID like '" + DepartmentID + "%'";
            }

        }
        string type = ddlUnitType.SelectedValue.ToString();
        //DBCls db = new DBCls();
        //string sql = "select PerformanceID,KeyUnitName,PerformanceState from Performance where DepartmentID='" + DepartmentID + "' and KeyUnitTypeID ='" + type + "'";
        try
        {
            //dt_sta = db.QueryDataTable(sql, "Performance");
            if (type == "全部")
            // where = "DepartmentID='" + DepartmentID + "'";
            {

                where = where;
            }
            else
                // where = "DepartmentID='" + DepartmentID + "' and KeyUnitTypeID ='" + type + "'";
                where = where + " and KeyUnitTypeID ='" + type + "'";

            //完成情况
            string perState = rblState.SelectedValue;
            if (perState == "已完成")
                where += " and PerformanceState='已完成'";
            else if (perState == "未完成")
                where += " and PerformanceState='未完成'";
            else
                where = where;

            //时间
            if (txtTimeFrom.Text != "" && txtTimeTo.Text != "")
            {
                try
                {
                    DateTime dtime1 = Convert.ToDateTime(txtTimeFrom.Text);
                    DateTime dtime2 = Convert.ToDateTime(txtTimeTo.Text);
                    DateTime dtFrom = dtime1 < dtime2 ? dtime1 : dtime2;
                    DateTime dtTo = dtime1 > dtime2 ? dtime1 : dtime2;
                    where += " and ( writetime >='" + dtFrom + "' and writetime <= '" + dtTo + "' )";
                }
                catch
                {
                    Response.Write("<script language=javascript>alert('时间格式不正确！')</script>");
                }
            }

            //where += " order by writetime desc";


            lblTempWhere.Text = where;

            gvBind(where, 0);

        }
        catch (Exception ex)
        {
            Response.Write("<script language=javascript>alert('gvBind错误" + ex.Message + "！')</script>");
            return;
        }

    }

    #endregion

    private void BindTable()
    {
        DataTable dtb = new DataTable();
        SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
        SqlCommand cmd = new SqlCommand("GetPowerTotal11", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter dap = new SqlDataAdapter(cmd);
        dap.Fill(dtb);

        //this.GridView1.DataSource = dtb;
        //this.GridView1.DataBind();
        DataTable dt = dtb.Copy();

        //添加汇总行
        DataRow dr = dtb.NewRow();
        dr[0] = "合计";

        for (int i = 0; i < dtb.Rows.Count; i++)
        {
            for (int j = 0; j < dtb.Rows[i].ItemArray.Count(); j++)
            {
                if (i == 0 || j == 0)
                {
                    string temp = dtb.Rows[i][j].ToString();
                    string[] str = temp.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (str.Length > 1)
                    {
                        dtb.Rows[i][j] = str[0].ToString();
                    }
                }
                //string temp = GridView1.Rows[i].Cells[j].Text;
                //GridView1.Rows[i].Cells[j].Text="<a href='#'>"+temp+"</a>";

                if (j != 0)
                {
                    if (dr[j].ToString() == "")
                        dr[j] = 0;
                    dr[j] = Convert.ToInt32(dr[j]) + Convert.ToInt32(dtb.Rows[i][j].ToString());
                }
            }


        }
        dtb.Rows.Add(dr);
        //dr[0] = "汇总";

        this.GridView1.DataSource = dtb;
        this.GridView1.DataBind();



        for (int i = 0; i < GridView1.Rows.Count - 1; i++)
        {
            for (int j = 1; j < GridView1.Rows[i].Cells.Count; j++)
            {
                string temp = GridView1.Rows[i].Cells[j].Text;
                string url = dt.Rows[i][0].ToString();
                string departmentID = url.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)[1].ToString();
                string[] type = GridView1.HeaderRow.Cells[j].Text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (type.Length > 1)
                {
                    GridView1.Rows[i].Cells[j].Text = "<a href='ListView.aspx?DepartmentID=" + departmentID + "&TypeID=" + type[1].ToString() + "'>" + temp + "</a>";
                }
            }
        }

        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            string[] temp = GridView1.HeaderRow.Cells[i].Text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (temp.Length > 1)
                GridView1.HeaderRow.Cells[i].Text = temp[0].ToString();
        }

    }
    private void BindKeyUnitType()
    {
        //SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
        //SqlCommand cmd = new SqlCommand("Select * From KeyUnitType Order by  cast(KeyUnitTypeID as int)", con);
        //cmd.CommandType = CommandType.Text;
        //SqlDataAdapter dap = new SqlDataAdapter(cmd);
        //DataTable dtb = new DataTable();
        //dap.Fill(dtb, "unittype");
        //this.Repeater1.DataSource = dtb;
        //this.Repeater1.DataBind();
    }
    private void BindChar(DataSet ds)
    {

        BindTable();
        //SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
        //SqlCommand cmd = new SqlCommand("KeyUnit5Power1", con);
        //cmd.CommandType = CommandType.StoredProcedure;
        //SqlDataAdapter dap = new SqlDataAdapter(cmd);
        //DataSet dst = new DataSet();
        //dap.Fill(dst, "units");

        DataView vw = ds.Tables[0].DefaultView;
        DataView vw2 = ds.Tables[1].DefaultView;
        DataView vw3 = ds.Tables[2].DefaultView;
        UserChart.Titles["Title"].Text = "各单位完成情况统计表";
        UserChart.ChartAreas["Default"].AxisX.LabelsAutoFit = false;
        UserChart.Series["支队完成率"].Points.DataBindXY(vw, "ShortName", vw, "Score");
        UserChart.Series["大队完成率"].Points.DataBindXY(vw2, "ShortName", vw2, "Score");
        UserChart.Series["派出所完成率"].Points.DataBindXY(vw3, "ShortName", vw3, "Score");
        for (int i = 0; i < vw.Count; i++)
        {
            UserChart.Series["支队完成率"].Points[i].Href = "../KeyUnit/KeyUnitList2.aspx?DepartmentID=" + vw[i][1].ToString() + "&Flag=1";
            UserChart.Series["大队完成率"].Points[i].Href = "../KeyUnit/KeyUnitList2.aspx?DepartmentID=" + vw2[i][1].ToString() + "&Flag=2";
            UserChart.Series["派出所完成率"].Points[i].Href = "../KeyUnit/KeyUnitList2.aspx?DepartmentID=" + vw3[i][1].ToString() + "&Flag=3";

        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        DBCls db = new DBCls();
        string sql=txtSql.Text;
        dt.Clear();
        dt = db.QueryDataTable(sql, "test");
        if (dt.Rows.Count > 0)
        {
            gvDW.DataSource = dt;
            gvDW.DataBind();
        }
    }
}
